#ifndef LED_H
#define LED_H


#include <WProgram.h>
#include <inttypes.h>
#include <math.h>

#define ID_LED_BLUE      9
#define ID_LED_RED      10
#define ID_LED_GREEN    11

class LEDcontrol
{
public:
	LEDcontrol(); // constructor
	void changeColor(int,int,int); //
	int* getColor();
	void fadeTo(int, int, int, unsigned long, int);
	
private:
	int _rgb[3];
};

LEDcontrol::LEDcontrol()
{
    pinMode(ID_LED_RED, OUTPUT);
    pinMode(ID_LED_GREEN, OUTPUT);
	pinMode(ID_LED_BLUE, OUTPUT);
    
    digitalWrite(ID_LED_RED, LOW);
    digitalWrite(ID_LED_GREEN, LOW);
	digitalWrite(ID_LED_BLUE, LOW);
	
	_rgb[0] = 0;
	_rgb[1] = 0;
	_rgb[2] = 0;
}

void LEDcontrol::changeColor(int r, int g=0, int b =0)
{
	if(r > 0) _rgb[0] = r&0xff; else _rgb[0] = 0;
	if(g > 0) _rgb[1] = g&0xff; else _rgb[1] = 0;
	if(b > 0) _rgb[2] = b&0xff; else _rgb[2] = 0;
	
	analogWrite(ID_LED_RED, _rgb[0]);
	analogWrite(ID_LED_GREEN, _rgb[1]);
	analogWrite(ID_LED_BLUE, _rgb[2]);
}

int* LEDcontrol::getColor()
{
	return _rgb;
}

void LEDcontrol::fadeTo(int r = 0, int g = 0, int b = 0, unsigned long t = 1000, int _step = 10)
{
	int tmp[3] = {_rgb[0],_rgb[1],_rgb[2]};
	
	if(r > 0) _rgb[0] = r&0xff; else _rgb[0] = 0;
	if(g > 0) _rgb[1] = g&0xff; else _rgb[1] = 0;
	if(b > 0) _rgb[2] = b&0xff; else _rgb[2] = 0;
	
	long dt = t/_step;
	int dr = ceil((_rgb[0]-tmp[0])/_step);
	int dg = ceil((_rgb[1]-tmp[1])/_step);
	int db = ceil((_rgb[2]-tmp[2])/_step);
	
	for(int i = 0; i < _step; i++)
	{
		analogWrite(ID_LED_RED, tmp[0]+dr*i);
		analogWrite(ID_LED_GREEN, tmp[1]+dg*i);
		analogWrite(ID_LED_BLUE, tmp[2]+db*i);
		delay(dt);
	}
	
	analogWrite(ID_LED_RED, _rgb[0]);
	analogWrite(ID_LED_GREEN, _rgb[1]);
	analogWrite(ID_LED_BLUE, _rgb[2]);
}
#endif
